<template>
  <el-dialog :model-value="visible" :title="title" width="500" :close-on-click-modal="false" :show-close="false">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
      <el-form-item label="用户姓名" prop="realName">
        <el-input readonly :model-value="props.realName"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="再次输入" prop="checkPassword">
        <el-input v-model="form.checkPassword"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit">提交</el-button>
        <el-button @click="emits('close', false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import ApiTree from '@/server/api-tree';
import { type FormRules, type FormInstance, ElMessage } from 'element-plus';
import { reactive, ref, watch } from 'vue';

const emits = defineEmits(["close"])
const props = withDefaults(defineProps<{ guid: string, realName: string, visible: boolean }>(), {
  guid: "",
  realName: "",
  visible: false
})
/** 表单定义 */
const title = ref<string>("修改用户密码");
const form = ref<{ guid: string, password: string, checkPassword: string }>({
  guid: "",
  password: "",
  checkPassword: "",
});
const formRef = ref<FormInstance>();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const passwordValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("密码不能为空"))
  }
  if (typeof value === 'string' && (value.length < 6 || value.length > 20)) {
    return callback(new Error("密码长度必须在6-20位之间,且必须包含字母和数字"))
  }
  if (!(/[a-zA-Z]/.test(value) && /[0-9]/.test(value))) {
    return callback(new Error("密码长度必须在6-20位之间,且必须包含字母和数字"))
  }
  callback();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const checkPasswordValidator = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error("二次密码不能为空"))
  }
  if (value !== form.value.password) {
    return callback(new Error("两次密码不一致"))
  }
  callback();
}
const formRules = reactive<FormRules<{ password: string, checkPassword: string }>>({
  password: [{ required: true, validator: passwordValidator }],
  checkPassword: [{ required: true, validator: checkPasswordValidator }],
})
/**
 * 监听属性变化
 */
watch(() => props.visible, () => {
  form.value.password = "";
  form.value.checkPassword = "";
}, { immediate: true })
/**提交表单 */
const onSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      form.value.guid = props.guid;
      const { success, msg } = await ApiTree.user.updatePwd(form.value);
      if (success) {
        ElMessage.success(msg);
      }
      emits("close", success);
    }
  })
}
</script>
<style lang="scss" scope></style>
